package com.sirui.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

public class CmdUtils {
    public static void main(String[] args) throws IOException {
        //Arrays.stream(args).forEach(System.out::println);
        if (args.length > 0) {
            killProcess(args[0]);
        } else {
            killProcess("8090");
        }
    }

    public static void killProcess(String port) throws IOException {
        String cmd1 = "cmd /c netstat -ano | findstr " + port;
        ArrayList<String> rList = runCmd(cmd1);
        if (rList.size() == 0) {
            System.out.println("未查询到端口:" + port);
            return;
        }
        String str = rList.get(0);
        String pid = str.substring(str.lastIndexOf(" "));
        String cmd2 = "cmd /c tasklist|findstr " + pid;
        ArrayList<String> rList1 = runCmd(cmd2);
        String str1 = rList1.get(0);
        String cmd3 = "taskkill /pid " + pid + " -f";
        ArrayList<String> rList2 = runCmd(cmd3);
        String str2 = rList2.get(0);
        //System.out.println(pid);
        System.out.println(str);
        System.out.println(str1);
        System.out.println(str2);
    }

    public static ArrayList<String> runCmd(String command) throws IOException {
        ArrayList<String> result = new ArrayList<>();
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command);
        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(proc.getInputStream(), Charset.forName("GBK")));
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            //String s1 = new String(s.getBytes("ISO-8859-1"), "UTF-8");
            result.add(s);
        }
        return result;
    }
}
